/**
 * Created with IntelliJ IDEA.
 * User: duoba
 * Date: 16/2/24
 * Time: 上午11:02
 * To change this template use File | Settings | File Templates.
 */

package com.cake21.uitest.System.Core;

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Config {
    /*文档对象*/
    private Document doc = null;

    /*构建方法*/
    public Config(String fileName) {
        try {
            FileInputStream inputStream = new FileInputStream(new File(fileName));
            /*读取XML格式配置文件*/
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = docBuilder.parse(inputStream);
        } catch (Exception e) {
            /*配置文件读取错误*/
            e.printStackTrace();
        }
    }

    /*构建方法2*/
    public Config(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
			/*读取XML格式配置文件*/
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = docBuilder.parse(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*构建方法3*/
    public Config(InputStream is) {
        try {
            /*读取XML格式配置文件*/
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = documentBuilder.parse(is);
        } catch (Exception e) {
            /*配置文件读取错误*/
            e.printStackTrace();
        }
    }

    /*读取节点文本值*/
    public String readTag(String tagName) {
        NodeList list = doc.getElementsByTagName(tagName);
        if (list.getLength() > 0) {
            // 如果有多个节点名称相同，只读取第一个节点
            return list.item(0).getFirstChild().getNodeValue().toString();
        }
        return "";
    }

    /*读取节点列表*/
    public NodeList readTags(String tagName) {
        return doc.getElementsByTagName(tagName);
    }

    /*获取节点文本值*/
    public static String getNodeString(Node node) {
        return (node != null) ? node.getNodeValue().toString() : "";
    }
}
